<template>
  <div class="edit-popup">
    <popup
        ref="popupRef"
        :title="popupTitle"
        :async="true"
        width="400px"
        :clickModalClose="true"
        @confirm="handleSubmit"
        @close="handleClose"
    >
      <el-form ref="formRef" :model="formData" label-width="84px" :rules="formRules">
        <el-form-item label="客户名称" prop="accountName">
          <el-input v-model="formData.accountName"/>
        </el-form-item>
        <el-form-item label="附件">
          <el-button type="primary" @click="handleSubmit">文件上传</el-button>
        </el-form-item>
        <el-form-item label="文件名称">
          <el-input v-model="formData.fileName"/>
        </el-form-item>
        <el-form-item label="文件类型">
          <el-input v-model="formData.fileType"/>
        </el-form-item>
        <el-form-item label="文件描述">
          <el-input v-model="formData.fileDescriptor" type="textarea"/>
        </el-form-item>
        <!--<el-form-item label="上传者">-->
        <!--  <el-input v-model="formData.uploader"/>-->
        <!--</el-form-item>-->
        <!--<el-form-item label="操作人">-->
        <!--  <el-input v-model="formData.userName"/>-->
        <!--</el-form-item>-->
      </el-form>
    </popup>
  </div>
</template>
<script lang="ts" setup>
import type {FormInstance} from 'element-plus'
import {fileEdit, fileAdd, fileDetail} from '@/api/syfile'
import Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import type {PropType} from 'vue'

defineProps({
  dictData: {
    type: Object as PropType<Record<string, any[]>>,
    default: () => ({})
  }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
  return mode.value == 'edit' ? '编辑客户文件' : '新增客户文件'
})

const formData = reactive({
  id: '',
  fileDescriptor: '',
  fileName: '',
  accountName: '',
  uploader: '',
  uploadTime: '',
  fileType: '',
  userName: '',
  createTime: ''
})

const formRules = {
  accountName: [
    {
      required: true,
      message: '请输入客户名称',
      trigger: ['blur']
    }
  ]
}

const handleSubmit = async () => {
  await formRef.value?.validate()
  const data: any = {...formData}
  mode.value == 'edit' ? await fileEdit(data) : await fileAdd(data)
  popupRef.value?.close()
  feedback.msgSuccess('操作成功')
  emit('success')
}

const open = (type = 'add') => {
  mode.value = type
  popupRef.value?.open()
}

const setFormData = async (data: Record<string, any>) => {
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      //@ts-ignore
      formData[key] = data[key]
    }
  }
}

const getDetail = async (row: Record<string, any>) => {
  const data = await fileDetail({
    id: row.id
  })
  setFormData(data)
}

const handleClose = () => {
  emit('close')
}

defineExpose({
  open,
  setFormData,
  getDetail
})
</script>
